package integral

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/setting/rpc/settingclient"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserTaskLogListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 获取香评列表,首页多香评展示
func NewGetUserTaskLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserTaskLogListLogic {
	return &GetUserTaskLogListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserTaskLogListLogic) GetUserTaskLogList(req *types.UserTaskLogListReq) (resp *types.UserTaskLogListResp, err error) {
	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	var filters []string
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}
	filters = append(filters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))

	var preload string = "userTransactionLog:Id,UserId,UserName,AssetType,ChangeType,ChangeAmount,OldAmount"
	preload += ",SourceType,SourceId,Desc,Status,CreatedAt,UpdatedAt"
	var eagerLoad string = "userTransactionLog:"

	var sorter *string
	if req.Sorter != nil {
		sorter = pointy.GetPointer(strings.TrimSpace(*req.Sorter))
	}
	var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini
	res, err := l.svcCtx.UserRpc.GetIntegralTaskLogList(l.ctx, &userclient.BaseListReq{
		Offset:     uint32((page - 1) * pageSize),
		Limit:      uint32(pageSize),
		Preload:    pointy.GetPointer(preload),
		EagerLoad:  pointy.GetPointer(eagerLoad),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     sorter,
		PlatformId: pointy.GetPointer(platformId),
	})
	if err != nil {
		return nil, err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}
	resp = &types.UserTaskLogListResp{
		BaseListInfo: types.BaseListInfo{
			Total:           res.Total,
			Current:         page,
			PageSize:        pageSize,
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}
	var points uint64
	if len(res.List) > 0 {
		for _, v := range res.List {
			resp.List = append(resp.List, &types.UserTaskLogInfo{
				Id:        v.Id,
				UserId:    v.UserId,
				TaskId:    v.TaskId,
				TaskName:  v.TaskName,
				TaskSlug:  v.TaskSlug,
				Gems:      v.Gems,
				Growth:    v.Growth,
				Integrals: v.Integrals,
				Status:    v.Status,
				CreatedAt: v.CreatedAt,
				UpdatedAt: v.UpdatedAt,
			})
			if v.Integrals != nil && *v.Integrals > 0 {
				points += *v.Integrals
			}
		}
	}

	settingPreload := "blogGeneralSetting:pointsRestrictToday"
	settingEagerLoad := "blogGeneralSetting:"
	setting, err := l.svcCtx.SettingRpc.SettingList(l.ctx, &settingclient.SettingListRequest{
		Preload:   settingPreload,
		EagerLoad: settingEagerLoad,
	})
	if err != nil {
		return nil, err
	}
	var pointsRestrict uint64
	if len(setting.Data) > 0 {
		pointsRestrict, err = strconv.ParseUint(setting.Data[0].Value, 10, 64)
	}
	//获取大于积分上限，说明积分出现问题 记录日志
	if pointsRestrict < points {
		logx.Errorf("GetUserTaskLogList points restrict err")
		resp.PointsRestrictToday = pointy.GetPointer(uint64(0))
	} else {
		resp.PointsRestrictToday = pointy.GetPointer(pointsRestrict - points)
	}
	return resp, nil
}
